<?php
	/**
	 * 购物车控制器
	 */
	class CartAction extends Action{

		//购物车视图
		public function index(){
			$this->data = $_SESSION['cart'];
			$this->display();
		}

		//处理加入购物车的货品
		//异步处理购物车中的商品总数量及价格
		public function goodsToCart(){
			if($this->isAjax()){
				$specIds = $this->_post('goodsSpecIds');
				$gid = $this->_post('gid');
				$attrIds = explode(',', ltrim($specIds ,','));
				$buyNumber = $this->_post('number','intval');
				$db = D('CartCont');
				$attr = $attrIds[0] . '|' . $attrIds[1];
				$where = 'goods.id = ' . $gid . ' and ' . 'goods_list.attr="'.$attr.'"' .'and goods_attr.id in('. $attrIds[0] .','. $attrIds[1] .')';
 				$result = $db->where($where)->select();
 				if(is_array($result)){
 					$gsSumPrice = $result[0]['sprice'];
 					foreach($result as $key=>$val){
	 					$gsSumPrice += (float)$val['price'];
	 					$spec[] = $val['value'];
 					}
 					$cartGsImgShow = explode('|', $result[0]['mini']);
	 				$usergoodsInfo = array(
	 					'gid'=>$result[0]['id'],
	 					'gname'=>$result[0]['name'],
	 					'gimg'=>$cartGsImgShow[0],
	 					'sprice'=>$gsSumPrice,
	 					'unit'=>$result[0]['unit'],
	 					'sprice'=>number_format($gsSumPrice , '2'),
	 					'number'=>$buyNumber,
	 					'totalPrice' =>number_format($buyNumber*$gsSumPrice ,'2'),
	 					'color'=>$spec[0],
	 					'size'=>$spec[1],
	 					'spec'=>$specIds
	 				);
	 				if($this->_post('where') == 'cart'){
	 					return number_format($gsSumPrice*$buyNumber,'2');
	 				}else{
	 					session_start();
						//session保存一天
						$lifeTime = 24 * 3600;
						setcookie(session_name(), session_id(), time() + $lifeTime, "/");
	 					$_SESSION['cart'][] =$usergoodsInfo;
	 					echo json_encode(array('status'=>'ok'));
	 				}
 				}else{
					echo json_encode(array('status'=>'er'));
				}
			}
		}
		// //异步处理购物车中的商品总数量及价格
		public function editBuyNum(){
			if($this->isAjax()){
				echo json_encode(array('totalPrice' => $this->goodsToCart()));
			}else{
				echo json_encode(array('status'=>'er'));
			}
		}

	}
?>
